﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using EntreeServer.Module;
using EntreeServer.Module.ActionTray;
using EntreeServer.Module.Configuration;
using EntreeServer.Module.Controls;
using Microsoft.SharePoint;
using System.Text.RegularExpressions;

namespace ME.SDK.SketchAction
{
    [Guid("94ac3b6d-05ac-49d9-96ea-0a5d27a4ae97")]
    public class AnnotateImage : ActionProvider
    {

        public override void QueryScope(ActionScopeObject scope, out ActionLaneCollection actionLanes, out ActionItemCollection actionItems)
        {
            actionLanes = null;
            actionItems = new ActionItemCollection();

            //Check scope for Detail screen
            if (scope.ScopeType == ScopeTypes.SharePoint.SPListItem_Details && scope.Properties.ContainsKey(EntreeServer.Module.ActionTray.ScopeProperties.SharePoint.SPListID))
            {
                SPList list = SPContext.Current.Web.Lists[new Guid(scope.Properties[EntreeServer.Module.ActionTray.ScopeProperties.SharePoint.SPListID])];
                //check that you are inside a document library
                if (list.BaseType == SPBaseType.DocumentLibrary)
                {
                    SPListItem item = list.GetItemById(int.Parse(scope.Properties[EntreeServer.Module.ActionTray.ScopeProperties.SharePoint.SPListItemID]));
                    //Check for image types
                    Regex rx = new Regex("\\.jpg|\\.jpeg|\\.png|\\.gif|\\.bmp|\\.tiff", RegexOptions.IgnoreCase);
                    if (rx.IsMatch(item.Name))
                    {
                        var action = new ActionItem("custom", "AnnotateCapture")
                        {
                            ClickAction = new EntreeClickActionObject(this)
                            {
                                TargetContextMenu = true
                            },
                            IconUrl = Icon,
                            Title = "Annotate Image",
                            Sequence = 999
                        };

                        action.ClickAction["ListGuid"] = list.ID.ToString();
                        action.ClickAction["ImageUrl"] = item.File.ServerRelativeUrl;
                        action.ClickAction["FileName"] = item.File.Name;
                        //add action to the action tray
                        actionItems.Items.Add(action);
                    }
                }
            }

        }

        public override void QueryList(EntreeScopeObject scope, EntreeListObject output)
        {
            output.ListStyle = EntreeListStyles.context_menu;
            output.ListTitle = "Annotate Image";

            output.ActionScope.ScopeType = "SketchCapture";
            //Check for save property, means the user has clicked the save button
            if (scope.Properties.ContainsKey("save"))
            {
                string filename = scope.FormProperties["filename"] + ".png";
                string base64img = scope.FormProperties["sketch"].Replace("data:image/png;base64,", "");
                SPList list = SPContext.Current.Web.Lists[new Guid(scope.Properties["ListGuid"])];
                try
                {
                    SPContext.Current.Web.AllowUnsafeUpdates = true;

                    byte[] bytes = System.Convert.FromBase64String(base64img);

                    SPFolder f = list.RootFolder;
                    SPFile doc = f.Files.Add(filename, bytes, true);
                    f.Update();
                    SPContext.Current.Web.AllowUnsafeUpdates = false;
                    output.ActionScope.TransferToApplication = true;
                }
                catch (Exception er)
                {
                    output.ListTitle = er.ToString();
                }
                
            }
            else
            {
                //Initial screen loaded from the action
                EntreeListGroup grp = output.AddListGroup();
                grp.ListGroupStyle = EntreeListGroupStyles.list;
                //Add a textbox to contain the filename
                EntreeTextBox fn = grp.AddFormItem<EntreeTextBox>("filename");
                fn.Name = "File Name";
                fn.Value = scope.Properties["FileName"] + "-Annotated";
                //Add the custom Canvas control
                grp = output.AddListGroup("Sketch in the Box");
                EntreeFormItem canvas = grp.AddFormItem("sketch");
                canvas.ListItemStyle = "Annotate.Canvas";
                canvas["BackgroundImage"] = scope.Properties["ImageUrl"];

                //Add Palette
                EntreeListItem p = grp.AddListItem();
                p.ListItemStyle = "Canvas.Palette";

                //Add the save button
                ActionItem save = new ActionItem();
                save.IconUrl = "/_layouts/images/EntreeServer/inc/at/at-save-32.png";
                save.ActionId = "SaveSketch";
                save.Title = "Save Sketch";
                save.ClickAction = new EntreeClickActionObject(this)
                {
                    FormSubmit = true,
                    TargetContextMenu = false
                };

                save.ClickAction["save"] = "yes";
                save.ClickAction["ListGuid"] = scope.Properties["ListGuid"];
                output.ActionTray.AddAction(save);

                ActionItem Palette = new ActionItem();
                Palette.ActionId = "OpenPalette";
                Palette.IconUrl = "/_layouts/images/ME.SDK.SketchAction/AnnotateImage/palette.png";
                Palette.Title = "Palette";
                Palette.ClickAction = new EntreeClientsideClickAction(this)
                {
                    TargetFunction = "OpenPalette"
                };

                output.ActionTray.AddAction(Palette);
            }
        }

        public override string Title
        {
            get
            {
                return "AnnotateImage";
            }
        }

        public override string PluginPath
        {
            get
            {
                return "/_layouts/images/ME.SDK.SketchAction/AnnotateImage";
            }
        }

        public String Icon
        {
            get
            {
                return "/_layouts/images/ME.SDK.SketchAction/AnnotateImage/sign.png";
            }
        }
    }
}
